const CFG = require('./config');
const FUN = require('./comm/func');
const fs = require('fs');
const mqttConn = require('./utils/mqttConn');//启动mqtt客户端

//等待mqtt连接完成，打开订阅
mqttConn.newClient('admin.'+FUN.rand(12345678,99999999),(conn)=>{
  let Topics=[];
  let mqttHd = require('./utils/devConfig');
  let i=0;

  //订阅主题
  Topics[i++]=mqttHd.CombTopic('cmdres',wDev);

  console.log('+++',Topics);
  conn.msgHdrs=[];
  conn.msgHdrs.push(require('./upgrade'));
  mqttHd.mqConn=conn;
  conn.subscribe(Topics,(err)=>{if(err)console.log('err4:',err)});

  //发出开始下载bin的命令
  mqttHd.PubCmd2Dev(wDev,'upgrade');
})


//--------------------------应用代码开始--------------------------
//根据参数开始处理文件
let fwDate = process.argv[2];//命令行入参解析
let wDev = process.argv[3];
let fwBuf = fs.readFileSync('D:/Administrator/Desktop/FLYClient/AllWin_20'+fwDate+'_00.bin');
let fwPageNum = parseInt(fwBuf.length/1024)+1;

//处理bin文件
let sum=0;
fwBuf.writeUInt32LE(fwBuf.length,9*4);//BB_SIZE
for(let i=0;i<fwBuf.length;i+=4){sum +=fwBuf.readUInt32LE(i);}
sum=Math.imul(Math.imul(sum,17)+23,sum)+33;
console.log('bin chksum',sum.toString(16));
fwBuf.writeUInt32LE(sum>>>0,10*4);//BB_SUM

//解析mq消息
function mqMsgIn(Path,Payload,pkt)
{
  if(Path.func=='cmdres')
  {
    let upCmd=Payload.toString().split(':');
    if(upCmd.length==2 && upCmd[0]=='getbin')
    {
      let mqttHd = require('./utils/devConfig');
      let Idx=parseInt(upCmd[1]);

      process.stdout.write('getbin:'+Idx+'\r');//不换行console.log

      if(Idx < fwPageNum)
      {
        let Buf=Buffer.alloc(1024+4);
        Buf.writeUInt32LE(Idx,0);
        fwBuf.copy(Buf,4,Idx*1024);

        mqttHd.PubBin2Dev(Path.devId,Buf);//发送bin文件块
      }
      else if(Idx == fwPageNum)
      {
        mqttHd.PubCmd2Dev(Path.devId,'reset');
        console.log('finish upgrade[%d]',Idx);
        setTimeout(()=>{process.exit()},2000);
      }
    }
  }
}

exports.mqMsgIn = mqMsgIn;